package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVPush;
import com.pocketsweet.R;
import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.C;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chat.ui.activity.ChatActivity;

import com.pocketsweet.chatui.domain.User;
import com.pocketsweet.dao.SystemConfigManager;
import com.pocketsweet.model.MLGallery;
import com.pocketsweet.model.MLReportRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLUserCount;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.model.MLVoice;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.fragments.NewOnlineFragment;
import com.pocketsweet.ui.fragments.SelfFragment;
import com.pocketsweet.ui.uilib.ActionSheetDialog;
import com.pocketsweet.ui.uilib.ActionSheetDialog.OnSheetItemClickListener;
import com.pocketsweet.ui.uilib.ActionSheetDialog.SheetItemColor;
import com.pocketsweet.ui.uilib.BaZhangTuView;
import com.pocketsweet.ui.uilib.FlowLayout;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.SpecialTagView;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.adapter.VoiceAdapter;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * @author hantian 个人信息页面
 */
@ContentView(R.layout.activity_profile)
public class Profile extends BaseActivity implements OnClickListener,
        SensorEventListener {

    @ViewInject(R.id.mainHeader)
    private static HeaderLayout header;

    @ViewInject(R.id.tvLoading)
    private static TextView tvLoading;

    @ViewInject(R.id.tvUserAge)
    private static TextView tvUserAge;

    @ViewInject(R.id.tvFrom)
    private static TextView tvFrom;

    @ViewInject(R.id.tvStar)
    private static TextView tvStar;

    @ViewInject(R.id.tvIsTestLover)
    private static TextView tvIsTestLover;

    @ViewInject(R.id.linOtherView)
    private static LinearLayout linOtherView;

    @ViewInject(R.id.llLike)
    private static LinearLayout llLike;

    @ViewInject(R.id.llReport)
    private static LinearLayout llReport;

    @ViewInject(R.id.linCall)
    private static LinearLayout linCall;

    @ViewInject(R.id.linMolianNumber)
    private static LinearLayout linMolianNumber;

    @ViewInject(R.id.linSign)
    private static LinearLayout linSign;

    @ViewInject(R.id.linBelong)
    private static LinearLayout linBelong;

    @ViewInject(R.id.linCallMe)
    private static LinearLayout linCallMe;

    @ViewInject(R.id.linLike)
    private static LinearLayout linLike;

    @ViewInject(R.id.linSpecical)
    private static LinearLayout linSpecical;

    @ViewInject(R.id.linLook)
    private static LinearLayout linLook;

    @ViewInject(R.id.linJob)
    private static LinearLayout linJob;

    @ViewInject(R.id.linLanguage)
    private static LinearLayout linLanguage;

    @ViewInject(R.id.linVoice)
    private static LinearLayout linVoice;

    @ViewInject(R.id.ivIsLiked)
    private static TextView ivIsLiked;

    @ViewInject(R.id.tvLikeCount)
    private static TextView tvLikeCount;

    @ViewInject(R.id.tvAfter)
    private static TextView tvAfter;

    @ViewInject(R.id.molianNumber)
    private static TextView tvMolianNumber;

    @ViewInject(R.id.tvSign)
    private static TextView tvSign;

    @ViewInject(R.id.tvBelong)
    private static TextView tvBelong;

    @ViewInject(R.id.tvCallMe)
    private static TextView tvCallMe;

    @ViewInject(R.id.tvHeight)
    private static TextView tvHeight;

    @ViewInject(R.id.tvWeight)
    private static TextView tvWeight;

    @ViewInject(R.id.tvFigure)
    private static TextView tvFigure;

    @ViewInject(R.id.tvLanguage)
    private static TextView tvLanguage;

    // @ViewInject(R.id.tvLike)
    // private static TextView tvLike;

    @ViewInject(R.id.flowSpecial)
    private static FlowLayout flowSpecial;

    @ViewInject(R.id.flowLike)
    private static FlowLayout flowLike;

    @ViewInject(R.id.tvJob)
    private static TextView tvJob;

    @ViewInject(R.id.userGallery)
    public static BaZhangTuView mGalleryView;

    @ViewInject(R.id.voiceListView)
    private static ListView voiceListView;

    private MLGallery curGallery;
    private MLGallery mlGallery = new MLGallery();
    public static Profile userProfileInstance = null;

    private MLUser mlUser = new MLUser();
    public static LoadingDailog loading;
    String userId;
    String nickname;
    public static boolean needUpdate = true;
    MLReportRecord mlReportRecord;
    public static int status;

    private AudioManager audioManager;// 监听听筒模式
    private SensorManager mSensorManager;
    private Sensor mSensor;

    private VoiceAdapter voiceAdapter;
    private MLVoice mlVoice = new MLVoice();
    public static ArrayList<String> imgsPath = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络
    public static List<AVFile> mlAVFileList = new LinkedList<AVFile>();// 已有的文件列表,
    // 将值传给编辑页面，编辑页面不用再请求网络
    private String likeCount;
    private boolean isLiked;
    private String position;
    User contectUser;
    private ArrayList<String> specialList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络
    private ArrayList<String> likeList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        userProfileInstance = this;
        // 如果不在这里写，总是报tab的onsizechange方法的错
        loading = ToolKits.createLoadingDialog(Profile.this, "提交中..");
        loading.setText("加载中");
        loading.show();
        tvLoading.setVisibility(View.VISIBLE);
        setHeaderFunction();
        initListener();
        voiceAdapter = new VoiceAdapter(this, Main.voiceList, false);
        voiceListView.setAdapter(voiceAdapter);
        voiceListView.setCacheColorHint(0);
        if (mlAVFileList != null) {
            mlAVFileList.clear();
        }
        Intent intent = getIntent();
        userId = intent.getStringExtra("userId");
        nickname = intent.getStringExtra("nickname");
        // likeCount = intent.getStringExtra("likeCount");
        if (userId == null) {
            userId = UserService.getCurrentUserId();
        }
        needUpdate = true;
        if (!userId.equals(UserService.getCurrentUserId())) {
            AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
            query.getInBackground(userId, new GetCallback<MLUser>() {
                @Override
                public void done(MLUser user, AVException e) {
                    if (e == null) {
                        mlUser = user;
                        postMaiDian();
                        // if (StringUtils.isEmpty(likeCount)) { // 判断传值是否有喜欢的次数
                        // getUserLikeCount();
                        // } else { // 如果没有，则获取网络数据
                        initVoice(true);
                        // }
                    } else {
                        // Log.e("==error", "can not get user" +
                        // e.getMessage());
                        // e.printStackTrace();
                        loading.dismiss();
                    }
                }
            });
            setHeaderRightComplain();// 如果不是自己，就显示投诉
        } else {
            mlUser = UserService.getCurrentUser();
            initVoice(false);
            setHeaderRightFunction();// 如果是自己，就显示编辑
        }

    }

    private void initListener() {
        audioManager = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    }

    protected void postMaiDian() {
        if (mlUser.getType() == C.USER_TYPE_NORMAL) {
            AVAnalytics.onEvent(this, "实习恋人个人资料页面访问");
        } else {
            AVAnalytics.onEvent(this, "空闲恋人个人资料页面访问");
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        mSensorManager.registerListener(this, mSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
        super.onResume();
        if (userId.equals(UserService.getCurrentUserId())) {
            // if (needUpdate == true) {
            mlUser = UserService.getCurrentUser();
            initVoice(false);
            // }
        }

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        mSensorManager.unregisterListener(this);
        super.onPause();
    }

    public String getCurUserId() {
        return mlUser.getObjectId();
    }

    public void setHeaderFunction() {
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        header.init(HeaderStyle.IMG_TITLE_TEXT);
        header.setMiddleText(nickname);
        // header.setRelBgAlpha();//设置背景透明
        header.setRightText("");
        header.setLeftContainerClickListener(new onLeftContainerListener() {

            @Override
            public void onClick() {
                Profile.this.finish();
            }
        });
    }

    public void setHeaderRightFunction() { // 设置右边编辑的跳转
        header.setRightText("编辑");
        header.setMiddleText(nickname);
        header.setRighttContainerClickListener(new onRightContainerListener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(Profile.this, ProfileEdit.class);
                intent.putStringArrayListExtra("imgsPath", imgsPath);
                // intent.putStringArrayListExtra("voice", voiceList);
                startActivity(intent);
            }
        });
    }

    public void setHeaderRightComplain() { // 设置右边编辑的跳转
        // header.setRightText("举报");
        header.setRightText("");
        header.setMiddleText(nickname);
        header.setRighttContainerClickListener(new onRightContainerListener() {
            @Override
            public void onClick() {
                new ActionSheetDialog(Profile.this)
                        .builder()
                        .setTitle("举报类型")
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("垃圾广告", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("垃圾广告");
                                    }
                                })
                        .addSheetItem("色情欺诈", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("色情欺诈");
                                    }
                                })
                        .addSheetItem("骚扰谩骂", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("骚扰谩骂");
                                    }
                                })
                        .addSheetItem("政治敏感", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("政治敏感");
                                    }
                                }).show();
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        if (Main.mMediaPlayer == null) {
            return;
        }
        if (Main.MediaTimer != null || Main.mMediaPlayer.isPlaying()) {
            Main.mMediaPlayer.pause();
            Main.mMediaPlayer.stop();
            Main.mMediaPlayer.reset();
            if (Main.MediaTimer != null) {
                Main.MediaTimer.cancel();
            }
        }
    }

    private void complain(final String type) { // 举报别人
        AVQuery<MLReportRecord> query = new AVQuery<MLReportRecord>(
                "MLReportRecord");
        query.whereEqualTo("reportee", mlUser);
        query.whereEqualTo("reporter", UserService.getCurrentUser());
        query.findInBackground(new FindCallback<MLReportRecord>() {

            @Override
            public void done(List<MLReportRecord> mlReportRecords, AVException e) {
                if (e == null) {
                    if (mlReportRecords.size() > 0) { // 若本用户以前举报过
                        mlReportRecord = mlReportRecords.get(0);
                    } else { // 没举报过
                        mlReportRecord = new MLReportRecord();
                    }
                    mlReportRecord.setRemark(type);
                    mlReportRecord.setReporter(UserService.getCurrentUser());
                    MLUser temp = new MLUser();
                    temp.setObjectId(mlUser.getObjectId());
                    mlReportRecord.setReportee(temp);
                    mlReportRecord.setStatus(C.REPORT_RECORD);
                    mlReportRecord.saveInBackground(new SaveCallback() {

                        @Override
                        public void done(AVException arg0) {
                            // method stub
                            if (arg0 == null) {
                                Map<String, Object> params = new HashMap<String, Object>();
                                final String userId = mlUser.getObjectId();
                                params.put("userId", userId);
                                AVCloud.callFunctionInBackground("reportUser",
                                        params, new FunctionCallback<Object>() {

                                            @Override
                                            public void done(Object arg0,
                                                             AVException e) {
                                                if (e == null) {
                                                    ToolKits.toast(
                                                            Profile.this,
                                                            "举报成功");
                                                    sendComplainSucceed(); // 发送举报成功消息
                                                    AVAnalytics.onEvent(
                                                            Profile.this, "举报");
                                                } else {
                                                    ToolKits.toast(
                                                            Profile.this,
                                                            "网络错误，请稍后重试");
                                                }
                                            }
                                        });
                            } else {
                                ToolKits.toast(Profile.this, "网络错误，请稍后重试");
                            }
                        }
                    });
                } else {
                    ToolKits.toast(Profile.this, "网络错误，请稍后重试");
                }
            }
        });
    }

    // 发送举报成功消息
    private void sendComplainSucceed() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("touserId", UserService.getCurrentUserId());
        params.put("type", 3);
        AVCloud.callFunctionInBackground("sendSysMsg", params,
                new FunctionCallback<Object>() {

                    @Override
                    public void done(Object arg0, AVException e) {
                        if (e == null) {
                            SystemConfigManager.getInstance(Profile.this)
                                    .setFirstLogin(false);
                        }

                    }
                });
    }

    private void getUserLikeCount() {
        final AVQuery<MLUserCount> queryCount = new AVQuery<MLUserCount>(
                "MLUserCount");
        queryCount.whereEqualTo("user", mlUser);
        queryCount.findInBackground(new FindCallback<MLUserCount>() {

            @Override
            public void done(List<MLUserCount> list, AVException arg1) {
                if (arg1 == null) {
                    if (list.size() > 0) {
                        likeCount = String.valueOf(list.get(0).getLikeCount());
                    } else {
                        likeCount = "0";
                    }
                } else {
                    // Log.e("===", "错误: " + arg1.getMessage());
                }
                initView(true);
            }
        });

    }

    private void initView(boolean isOther) {
        if (UserService.getCurrentUser() == null) {
            return;
        }
        voiceAdapter.notifyDataSetChanged();
        if (StringUtils.isEmpty(String.valueOf(mlUser.getAgeNum()))) {
            tvUserAge.setVisibility(View.GONE);
        } else {
            tvUserAge.setText(String.valueOf(mlUser.getAgeNum()));
            tvUserAge.setVisibility(View.VISIBLE);
        }
        // 设置性别颜色
        // GradientDrawable d = (GradientDrawable) getResources().getDrawable(
        // R.drawable.shape_rectangle_bule);
        if (mlUser.getGender() == 1) {
            // d.setColor(getResources().getColor(R.color.border_bottom_blue));//
            // 设置颜色
            tvUserAge.setBackgroundResource(R.drawable.shape_rectangle_bule);
        } else if (mlUser.getGender() == 2) {
            // d.setColor(getResources().getColor(R.color.main_text_color));//
            // 设置颜色
            tvUserAge.setBackgroundResource(R.drawable.shape_rectangle_red);
        }
        // 设置星座
        if (StringUtils.isEmpty(mlUser.getConstellation())) {
            tvStar.setVisibility(View.GONE);
        } else {
            tvStar.setText(mlUser.getConstellation());
            tvStar.setVisibility(View.VISIBLE);
        }
        // 设置地理位置
        String location = mlUser.getLocationCity();
        if (StringUtils.isEmpty(location)) {
            location = mlUser.getLocationProvince();
        }
        tvFrom.setText(location);
        tvFrom.setVisibility(View.VISIBLE);
        if (StringUtils.isEmpty(location)) {
            tvFrom.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(String.valueOf(mlUser.getMolianId()))) {
            linCallMe.setVisibility(View.VISIBLE);
            tvMolianNumber.setText(String.valueOf(mlUser.getMolianId()));
        } else {
            linCallMe.setVisibility(View.GONE);
        }
        if (mlUser.getType() == C.USER_TYPE_NORMAL) {
            tvIsTestLover.setText("实习恋人");
        } else if (mlUser.getType() == C.USER_TYPE_LOVER) {
            tvIsTestLover.setText("口袋恋人");
        } else if (mlUser.getType() == C.USER_TYPE_RECOMMENDED) {
            tvIsTestLover.setText("梦想恋人");
        }
        if (!StringUtils.isEmpty(mlUser.getIntro())) {
            linSign.setVisibility(View.VISIBLE);
            tvSign.setText(mlUser.getIntro());
        } else {
            linSign.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(mlUser.getBelong())) {
            linBelong.setVisibility(View.VISIBLE);
            tvBelong.setText((mlUser.getBelong()));
        } else {
            linBelong.setVisibility(View.GONE);
        }
        if (mlUser.getCalledTags() != null && mlUser.getCalledTags().size() > 0) {

            StringBuffer called = new StringBuffer();
            for (String temp : mlUser.getCalledTags()) {
                called.append(temp + " ");
            }
            tvCallMe.setText(called);
            linCallMe.setVisibility(View.VISIBLE);
        } else {
            linCallMe.setVisibility(View.GONE);
        }
        boolean flag = false;
        if (!StringUtils.isEmpty(String.valueOf(mlUser.getHeight()))
                && !String.valueOf(mlUser.getHeight()).equals("0")) {
            tvHeight.setText(String.valueOf(mlUser.getHeight()) + "cm");
            tvHeight.setVisibility(View.VISIBLE);
            flag = true;
        } else {
            tvHeight.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(String.valueOf(mlUser.getWeight()))
                && !String.valueOf(mlUser.getWeight()).equals("0")) {

            tvWeight.setText(String.valueOf(mlUser.getWeight()) + "kg");
            tvWeight.setVisibility(View.VISIBLE);
            flag = true;
        } else {
            tvWeight.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(String.valueOf(mlUser.getFigure()))
                && !String.valueOf(mlUser.getFigure()).equals("null")) {
            tvFigure.setText(String.valueOf(mlUser.getFigure()));
            tvFigure.setVisibility(View.VISIBLE);
            flag = true;
        } else {
            tvFigure.setVisibility(View.GONE);
        }
        if (flag == true) {
            linLook.setVisibility(View.VISIBLE);
        } else {
            linLook.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(mlUser.getJob())) {
            tvJob.setText(mlUser.getJob());
            linJob.setVisibility(View.VISIBLE);
        } else {
            linJob.setVisibility(View.GONE);
        }
        specialList.clear();
        if (mlUser.getSpecial() != null && mlUser.getSpecial().size() > 0) {
            for (String like : mlUser.getSpecial()) {
                specialList.add(like);
            }
            initSpecialTag();
            linSpecical.setVisibility(View.VISIBLE);
        } else {
            linSpecical.setVisibility(View.GONE);
        }
        likeList.clear();
        if (mlUser.getLikeTags() != null && mlUser.getLikeTags().size() > 0) {
            for (String like : mlUser.getLikeTags()) {
                likeList.add(like);
            }
            initlikeTag();
            linLike.setVisibility(View.VISIBLE);
        } else {
            linLike.setVisibility(View.GONE);
        }
        // if (mlUser.getLikeTags() != null && mlUser.getLikeTags().size() > 0)
        // {
        // StringBuffer like = new StringBuffer();
        // for (String tempLike : mlUser.getLikeTags()) {
        // like.append(tempLike + " ");
        // }
        // tvLike.setText(like);
        // linLike.setVisibility(View.VISIBLE);
        // } else {
        // linLike.setVisibility(View.GONE);
        // }
        if (mlUser.getLanguage() != null && mlUser.getLanguage().size() > 0) {

            StringBuffer language = new StringBuffer();
            for (String temp : mlUser.getLanguage()) {
                language.append(temp + " ");
            }
            tvLanguage.setText(language);
            linLanguage.setVisibility(View.VISIBLE);
        } else {
            linLanguage.setVisibility(View.GONE);
        }
        if (isOther == false) { // 是自己
            linOtherView.setVisibility(View.GONE);
        } else {

            tvAfter.setText("聊天");
            linOtherView.setVisibility(View.VISIBLE);

            llLike.setOnClickListener(this);
            linCall.setOnClickListener(this);
            llReport.setOnClickListener(this);
            isLiked = MLContext.getUserLikeID(mlUser.getObjectId()) == 0 ? false
                    : true;
            if (isLiked) {
                setLikeSb();
            } else {
                setCancleLikeSb();
            }
            likeCount = String.valueOf(mlUser.getLikeCount());
            tvLikeCount.setText(likeCount);
            if (loading.isShowing()) {
                loading.dismiss();
                tvLoading.setVisibility(View.GONE);
            }
        }
        AVQuery<AVObject> query = new AVQuery<AVObject>("MLGallery");
        query.whereEqualTo("belong_to", mlUser);
        query.include("images");
        if (userId.equals(UserService.getCurrentUserId())) { // 如果是自己的资料，则赋值
            mlAVFileList = SelfFragment.mlAVFileList;
        }
        if (mlAVFileList != null && mlAVFileList.size() > 0) {
            mGalleryView.setImagePaths(SelfFragment.imgsPath);
            for (int i = 0; i < mlAVFileList.size(); i++) {
                if (mlAVFileList != null && mlAVFileList.get(i) != null
                        && mlAVFileList.get(i).getUrl() != null) {
                    mGalleryView.addImagePath(mlAVFileList.get(i).getUrl());
                    mGalleryView.addBigImagePath(mlAVFileList.get(i).getUrl());
                }
            }
            mGalleryView.setImage();
        } else {
            query.findInBackground(new FindCallback<AVObject>() {
                public void done(List<AVObject> gallery, AVException e) {
                    if (e == null) {
                        // 获取相册
                        if (gallery.size() != 0) {
                            curGallery = (MLGallery) gallery.get(0);
                            mlAVFileList = curGallery.getImages();
                            if (userId.equals(UserService.getCurrentUserId())) {
                                SelfFragment.mlAVFileList = mlAVFileList;
                            }
                            if (mlAVFileList != null) {
                                for (int i = 0; i < mlAVFileList.size(); i++) {
                                    // mGalleryView.addImagePath(mlAVFileList.get(
                                    // i).getUrl());
                                    mGalleryView.addImagePath(mlAVFileList.get(
                                            i).getThumbnailUrl(true, 100, 100));
                                    // .getThumbnailUrl(false, width/4,
                                    // width/4));
                                    // // width/4是设置图片缩小的程度
                                    mGalleryView.addBigImagePath(mlAVFileList
                                            .get(i).getUrl());
                                }
                                mGalleryView.setImage();
                                imgsPath = mGalleryView.getBigImagePaths();
                                mGalleryView.setVisibility(View.VISIBLE);

                            } else {
                            }
                            if (userId.equals(UserService.getCurrentUserId())) { // 如果是自己的资料，则赋值
                                SelfFragment.mlAVFileList = mlAVFileList;
                                SelfFragment.mGallery = curGallery;
                                SelfFragment.imgsPath = mGalleryView
                                        .getBigImagePaths();
                                // Log.e("==selfSize=",
                                // "SelfFragment.mlAVFileList:"
                                // + String.valueOf(SelfFragment.mlAVFileList
                                // .size()));

                            }
                        } else { // 没有相册的处理
                            // Log.e("===", "curGallery为0 ");
                            mGalleryView.setVisibility(View.GONE);

                        }
                        if (loading.isShowing()) {
                            loading.dismiss();
                            tvLoading.setVisibility(View.GONE);
                        }
                    } else {
                        // Log.e("===", "curGallery " + e.getMessage());
                        if (loading.isShowing()) {
                            loading.dismiss();
                            tvLoading.setVisibility(View.GONE);
                        }
                        // mGalleryView.setVisibility(View.GONE);

                    }
                }
            });
        }
    }

    private void initSpecialTag() {
        flowSpecial.clearAllViews();
        for (int i = 0; i < specialList.size(); i++) {
            final SpecialTagView itemView = new SpecialTagView(Profile.this);
            itemView.initBgColor(R.drawable.shape_rectangle_gray_fill);
            itemView.setText(specialList.get(i));
            flowSpecial.addView(itemView);

        }
    }

    private void initlikeTag() {
        flowLike.clearAllViews();
        for (int i = 0; i < likeList.size(); i++) {
            final SpecialTagView itemView = new SpecialTagView(Profile.this);
            itemView.initBgColor(R.drawable.shape_rectangle_gray_fill);
            itemView.setText(likeList.get(i));
            flowLike.addView(itemView);

        }
    }

    private void initVoice(final boolean isOther) {
        // if (Main.voiceList == null) {
        final AVQuery<MLVoice> query = new AVQuery<MLVoice>("MLVoice");
        query.whereEqualTo("belong_to", mlUser);
        query.findInBackground(new FindCallback<MLVoice>() {
            @Override
            public void done(List<MLVoice> list, AVException arg1) {
                if (arg1 == null) {
                    Main.voiceList.clear();
                    if (list.size() > 0) {
                        // for (MLVoice temp : list) {
                        Main.voiceList.add(list.get(list.size() - 1));
                        // break;// 保证只有一个声线
                        // }
                        voiceAdapter.notifyDataSetChanged();
                        linVoice.setVisibility(View.VISIBLE);
                    } else {
                        linVoice.setVisibility(View.GONE);
                    }
                } else {
                    // Log.e("＝＝错误", "查询错误: " + arg1.getMessage());

                }
                initView(isOther);
            }
        });
        // }else{
        // voiceAdapter.notifyDataSetChanged();
        // linVoice.setVisibility(View.VISIBLE);
        // }

        // 检查缩略图是否正确，用来更新
        String subavatar = mlUser.getSubAvatar();
        if (mlUser.getAvatar() != null && subavatar != null && !StringUtils.isEmpty(subavatar) && !subavatar.equals("null")) {
            String avatar = mlUser.getAvatar().getThumbnailUrl(true, 100, 100);
            if (subavatar == null || !subavatar.equals(avatar)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("userId", mlUser.getObjectId());
                AVCloud.callFunctionInBackground("creatSubAvatar", params,
                        new FunctionCallback<Object>() {

                            @Override
                            public void done(Object o, AVException e) {
                                if (e == null) {
                                    AVQuery<MLUser> query = new AVQuery<MLUser>(
                                            "_User");
                                    query.getInBackground(mlUser.getObjectId(),
                                            new GetCallback<MLUser>() {

                                                @Override
                                                public void done(MLUser newuser,
                                                                 AVException e) {
                                                    if (e == null) {
                                                        if (MLCache.isInChat(newuser
                                                                .getObjectId())) {
                                                            MLCache.getCache()
                                                                    .put(newuser
                                                                                    .getObjectId(),
                                                                            newuser.toJSONObject());
                                                        }
                                                    } else {
                                                        // Log.e("err",
                                                        // e.getMessage());
                                                    }

                                                }
                                            });

                                } else {
                                }
                            }

                        });
            }
        }
    }

    /*
     * 喜欢该对象，并保存该数据到leanCloud
     */
    private void likeSb(final MLUser user) {
        llLike.setClickable(false); // 正在点赞，不准重复点击
        Map<String, Object> params = new HashMap<String, Object>();
        final String userId = user.getObjectId();
        params.put("userId", userId);
        AVCloud.callFunctionInBackground("likeUser", params,
                new FunctionCallback<Object>() {

                    @Override
                    public void done(Object arg0, AVException e) {
                        if (e == null) {
                            Map<String, Object> params = new HashMap<String, Object>();
                            MLUser curUser = UserService.getCurrentUser();
                            params.put("touserId", userId);
                            params.put("fromuserId", curUser.getObjectId());
                            params.put("nick", curUser.getNickname());
                            AVCloud.callFunctionInBackground(
                                    "sendNewLikerMsg", params, null);
                            AVQuery pushQuery = AVInstallation.getQuery();
                            pushQuery.whereEqualTo("channels", userId);
                            AVPush push = new AVPush();
                            push.setQuery(pushQuery);
                            JSONObject data;
                            try {
                                data = new JSONObject(
                                        "{\"alert\": \""
                                                + UserService
                                                .getCurrentUser()
                                                .getNickname()
                                                + "喜欢了你，快去翻翻看\", \"sound\": \"default\",\"action\": \"com.pocketsweet.NEW_LIKE_PUSH\"}");
                                push.setData(data);

                                push.sendInBackground();

                            } catch (JSONException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                            int count = user.getLikeCount() + 1;
                            user.setLikeCount(count);
                            // if (position != null) {
                            // OnlineTestLoverActivity.userList
                            // .get(Integer
                            // .valueOf(position))
                            // .setLikeCount(count);
                            // } else {
                            boolean isNewOnLine = false;
                            if (NewOnlineFragment.userList != null && NewOnlineFragment.userList.size() > 0) {
                                for (int i = 0; i < NewOnlineFragment.userList
                                        .size(); i++) {
                                    if (user.getObjectId().equals(
                                            NewOnlineFragment.userList.get(i)
                                                    .getObjectId())) {
                                        NewOnlineFragment.userList.get(i)
                                                .setLikeCount(count);
                                        isNewOnLine = true;
                                        break;
                                    }
                                }
                            }
                            if (isNewOnLine == false) {
                                if (OnlineTestLoverActivity.userList != null && OnlineTestLoverActivity.userList.size() > 0) {

                                    for (int i = 0; i < OnlineTestLoverActivity.userList
                                            .size(); i++) {
                                        if (user.getObjectId().equals(
                                                OnlineTestLoverActivity.userList
                                                        .get(i).getObjectId())) {
                                            OnlineTestLoverActivity.userList.get(i)
                                                    .setLikeCount(count);
                                            break;
                                        }
                                    }
                                }
                            }

                            // }
                            likeCount = String.valueOf(user.getLikeCount());
                            setLikeSb(); // 喜欢该对象，设置红心
                            tvLikeCount.setText(String.valueOf(likeCount)); // 点赞数量加一
                            // ToolKits.toast(ctx,
                            // "点赞成功");
                            MLContext.saveUserLikeID(user.getObjectId());
                            MLContext.saveLike(MLContext.LIKE_TYPE_USER, user
                                    .getObjectId().toString());

                            llLike.setClickable(true); // 可点击了
                        } else {
                            ToolKits.toast(Profile.this, "喜欢失败，请检查网络");
                            llLike.setClickable(true); // 可点击了
                        }
                    }

                });
    }

    /*
     * 不喜欢该对象，并保存该数据到leanCloud
     */
    private void unLikeSb(final MLUser user) {
        llLike.setClickable(false); // 正在点赞，不准重复点击
        Map<String, Object> params = new HashMap<String, Object>();
        final String userId = user.getObjectId();
        params.put("userId", userId);
        AVCloud.callFunctionInBackground("disLikeUser", params,
                new FunctionCallback<Object>() {

                    @Override
                    public void done(Object arg0, AVException e) {
                        if (e == null) {
                            int count = user.getLikeCount() - 1;
                            user.setLikeCount(count);
                            // if (position != null) {
                            // OnlineTestLoverActivity.userList.get(
                            // Integer.valueOf(position))
                            // .setLikeCount(count);
                            // }else {
                            boolean isNewOnLine = false;
                            if (NewOnlineFragment.userList != null && NewOnlineFragment.userList.size() > 0) {
                                for (int i = 0; i < NewOnlineFragment.userList
                                        .size(); i++) {
                                    if (user.getObjectId().equals(
                                            NewOnlineFragment.userList.get(i)
                                                    .getObjectId())) {
                                        NewOnlineFragment.userList.get(i)
                                                .setLikeCount(count);
                                        isNewOnLine = true;
                                        break;
                                    }
                                }
                            }
                            if (isNewOnLine == false) {
                                if (OnlineTestLoverActivity.userList != null && OnlineTestLoverActivity.userList.size() > 0) {

                                    for (int i = 0; i < OnlineTestLoverActivity.userList
                                            .size(); i++) {
                                        if (user.getObjectId().equals(
                                                OnlineTestLoverActivity.userList
                                                        .get(i).getObjectId())) {
                                            OnlineTestLoverActivity.userList.get(i)
                                                    .setLikeCount(count);
                                            break;
                                        }
                                    }
                                }
                            }
                            likeCount = String.valueOf(user.getLikeCount());
                            tvLikeCount.setText(String.valueOf(likeCount)); // 点赞数量减一
                            setCancleLikeSb(); // 不喜欢该对象，取消红心
                            MLContext.deleteUserLikeID(user.getObjectId());
                            MLContext.deleteLike(MLContext.LIKE_TYPE_USER, user
                                    .getObjectId().toString());

                        } else {
                            ToolKits.toast(Profile.this, "取消喜欢失败，请检查网络");
                        }
                        llLike.setClickable(true); // 可点击了
                    }
                });

    }

    /*
     * 取消喜欢该对象，设置红心取消
     */
    private void setCancleLikeSb() {
        ivIsLiked.setBackgroundResource(R.drawable.btn_like_big_unpress);
        // tvLikeCount.setTextColor(getResources().getColor(R.color.grey));

    }

    /*
     * 喜欢该对象，设置红心
     */
    private void setLikeSb() {
        ivIsLiked.setBackgroundResource(R.drawable.btn_like_big_press);
        // tvLikeCount.setTextColor(getResources().getColor(
        // R.color.main_text_color_pink));

    }

    /*
     * 喜欢该对象，在MLUserLike表上添加或者删除纪录
     */
    private void setMLUserLike(final MLUser user) {
        final AVQuery<AVObject> query = new AVQuery<AVObject>("MLUserLike");
        query.whereEqualTo("likeUser", user);
        query.whereEqualTo("user", UserService.getCurrentUser());
        query.findInBackground(new FindCallback<AVObject>() {
            public void done(List<AVObject> avObjects, AVException e) {
                if (e == null) {
                    // Log.e("成功", "查询到" + avObjects.size() + " 条符合条件的数据");
                    if (avObjects.size() <= 0) { // 当用户以前没有喜欢过，则喜欢该对象
                        // likeSb(user); // 喜欢该对象，并保存该数据到leanCloud
                        MLUserLike like = new MLUserLike();
                        MLUser currentUser = new MLUser();
                        currentUser.setObjectId(UserService.getCurrentUserId());
                        like.setUser(currentUser);
                        MLUser temp = new MLUser();
                        temp.setObjectId(user.getObjectId());
                        like.setLikeUser(temp);
                        like.saveInBackground(new SaveCallback() {

                            @Override
                            public void done(AVException arg0) {
                                if (arg0 == null) {
                                    likeSb(user);
                                } else {
                                    llLike.setClickable(true);
                                }

                            }
                        });
                    } else { // 当用户已经喜欢过，则取消喜欢
                        avObjects.get(0).deleteInBackground(
                                new DeleteCallback() {

                                    @Override
                                    public void done(AVException arg0) {
                                        if (arg0 == null) {
//											setCancleLikeSb(); // 设置红心取消
                                            unLikeSb(user);
                                        } else {
                                            // Log.e("删除失败",
                                            // "查询错误: "
                                            // + arg0.getMessage());
                                            llLike.setClickable(true);
                                        }

                                    }
                                });
                    }
                } else {
                    llLike.setClickable(true);
                    // Log.e("失败", "查询错误: " + e.getMessage());
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llReport:
                // 点击举报
                new ActionSheetDialog(Profile.this)
                        .builder()
                        .setTitle("举报类型")
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("垃圾广告", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("垃圾广告");
                                    }
                                })
                        .addSheetItem("色情欺诈", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("色情欺诈");
                                    }
                                })
                        .addSheetItem("骚扰谩骂", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("骚扰谩骂");
                                    }
                                })
                        .addSheetItem("政治敏感", SheetItemColor.Gray,
                                new OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        complain("政治敏感");
                                    }
                                }).show();
                break;
            case R.id.llLike:
                // 点击喜欢
//                if (MLContext.getUserLikeID(mlUser.getObjectId()) != 0) { // 当用户已经被点赞过,则取消点赞
//                    unLikeSb(mlUser); // 不喜欢该对象
//                } else { // 当用户没点赞过,则点赞
//                    likeSb(mlUser); // 喜欢该对象，并保存该数据到leanCloud
//                }
                llLike.setClickable(false);
                setMLUserLike(mlUser); // 在MLLike表上添加或者删除纪录
                if (mlUser.getType() == C.USER_TYPE_NORMAL) {
                    AVAnalytics.onEvent(Profile.this, "喜欢实习恋人");
                } else {
                    AVAnalytics.onEvent(Profile.this, "喜欢口袋恋人");
                }
                break;
            case R.id.linCall:
                // 进入聊天页面
                JSONObject user = MLCache.getCache().getAsJSONObject(
                        mlUser.getObjectId());
                if (mlUser.getType() == C.USER_TYPE_NORMAL) {
                    AVAnalytics.onEvent(Profile.this, "实习恋人聊天按钮点击");
                } else {
                    AVAnalytics.onEvent(Profile.this, "口袋恋人聊天按钮点击");
                }
                if (user != null) {

                    try {
                        Intent chatIntent = new Intent(this, ChatActivity.class);
                        chatIntent.putExtra("userId", user.getString("objectId"));
                        chatIntent.putExtra("avatar", user.getString("subAvatar"));
                        chatIntent.putExtra("nickName", user.getString("nickname"));
                        startActivity(chatIntent);

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {

                    if (mlUser.getSubAvatar() == null
                            || mlUser.getSubAvatar().equals("")) {// 兼容上一版本

                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("userId", mlUser.getObjectId());

                        AVCloud.callFunctionInBackground("creatSubAvatar", params,
                                new FunctionCallback<Object>() {

                                    @Override
                                    public void done(Object o, AVException e) {
                                        if (e == null) {
                                            AVQuery<MLUser> query = new AVQuery<MLUser>(
                                                    "_User");
                                            query.getInBackground(
                                                    mlUser.getObjectId(),
                                                    new GetCallback<MLUser>() {

                                                        @Override
                                                        public void done(
                                                                MLUser newuser,
                                                                AVException e) {
                                                            if (e == null) {
                                                                MLCache.saveStranger(newuser);
                                                                JSONObject user1 = MLCache
                                                                        .getCache()
                                                                        .getAsJSONObject(
                                                                                mlUser.getObjectId());
                                                                if (user1 == null) {
                                                                    return;
                                                                }
                                                                try {
                                                                    Intent chatIntent = new Intent(
                                                                            Profile.this,
                                                                            ChatActivity.class);
                                                                    chatIntent
                                                                            .putExtra(
                                                                                    "userId",
                                                                                    user1.getString("objectId"));
                                                                    chatIntent
                                                                            .putExtra(
                                                                                    "avatar",
                                                                                    user1.getString("subAvatar"));
                                                                    chatIntent
                                                                            .putExtra(
                                                                                    "nickName",
                                                                                    user1.getString("nickname"));
                                                                    startActivity(chatIntent);
                                                                } catch (JSONException e1) {
                                                                    e1.printStackTrace();
                                                                }
                                                            } else {
                                                                // Log.e("err",
                                                                // e.getMessage());
                                                            }

                                                        }
                                                    });

                                        } else {
                                            ToolKits.toast(Profile.this,
                                                    "发送邀请失败，请检查网络");
                                        }
                                    }

                                });
                    } else {

                        MLCache.saveStranger(mlUser);
                        JSONObject user1 = MLCache.getCache().getAsJSONObject(
                                mlUser.getObjectId());

                        try {
                            Intent chatIntent = new Intent(this, ChatActivity.class);
                            chatIntent.putExtra("userId",
                                    user1.getString("objectId"));
                            chatIntent.putExtra("avatar",
                                    user1.getString("subAvatar"));
                            chatIntent.putExtra("nickName",
                                    user1.getString("nickname"));
                            startActivity(chatIntent);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                }

                break;
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        float range = event.values[0];
        if (range == mSensor.getMaximumRange()) {
            audioManager.setMode(AudioManager.MODE_NORMAL);// 外放模式
        } else {
            audioManager.setMode(AudioManager.MODE_IN_CALL);// 听筒模式
        }
    }
}
